package controllers

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"context"

	"github.com/k8gb-io/k8gb/controllers/utils"

	k8gbv1beta1 "github.com/k8gb-io/k8gb/api/v1beta1"
	discov1 "k8s.io/api/discovery/v1"
	netv1 "k8s.io/api/networking/v1"
	"k8s.io/apimachinery/pkg/types"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/event"
	"sigs.k8s.io/controller-runtime/pkg/handler"
	"sigs.k8s.io/controller-runtime/pkg/predicate"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
	externaldnsApi "sigs.k8s.io/external-dns/apis/v1alpha1"
)

// SetupWithManager configures controller manager
func (r *GslbReconciler) SetupWithManager(mgr ctrl.Manager) error {
	// Figure out Gslb resource name to Reconcile when non controlled Name is updated

	r.Recorder = mgr.GetEventRecorderFor("gslb-controller")

	endpointMapHandler := handler.EnqueueRequestsFromMapFunc(
		func(_ context.Context, a client.Object) []reconcile.Request {
			gslbList := &k8gbv1beta1.GslbList{}
			opts := []client.ListOption{
				client.InNamespace(a.GetNamespace()),
			}
			c := mgr.GetClient()
			err := c.List(context.TODO(), gslbList, opts...)
			if err != nil {
				log.Info().Msg("Can't fetch gslb objects")
				return nil
			}
			reconcileRequests := []reconcile.Request{}
		GslbLoop:
			for _, gslb := range gslbList.Items {
				for _, server := range gslb.Status.Servers {
					for _, service := range server.Services {
						if service.Name == a.GetLabels()[discov1.LabelServiceName] {
							reconcileRequests = append(reconcileRequests, reconcile.Request{
								NamespacedName: types.NamespacedName{
									Name:      gslb.Name,
									Namespace: a.GetNamespace(),
								},
							})
							continue GslbLoop
						}
					}
				}
			}
			return reconcileRequests
		})

	ingressMapHandler := handler.EnqueueRequestsFromMapFunc(
		func(_ context.Context, a client.Object) []reconcile.Request {
			return r.GslbIngressHandler.Handle(a)
		})

	return ctrl.NewControllerManagedBy(mgr).
		For(&k8gbv1beta1.Gslb{}).
		Owns(&netv1.Ingress{}).
		Owns(&externaldnsApi.DNSEndpoint{}).
		Watches(&discov1.EndpointSlice{}, endpointMapHandler).
		Watches(&netv1.Ingress{}, ingressMapHandler).
		WithEventFilter(predicate.Funcs{
			UpdateFunc: func(e event.TypedUpdateEvent[client.Object]) bool {
				if e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration() {
					return true
				}

				// Ignore reconciliation in case nothing has changed in k8gb annotations
				oldAnnotations := e.ObjectOld.GetAnnotations()
				newAnnotations := e.ObjectNew.GetAnnotations()
				reconcile := !utils.EqualPredefinedAnnotations(oldAnnotations, newAnnotations, k8gbAnnotations...)

				return reconcile
			},
		}).
		Complete(r)
}
